/*
 * file.c
 *
 *  Created on: 2009-5-13
 *      Author: hwg
 */

#include "../header/common.h"
/*打开文件 dir 为 文件的绝对路径 如果成功返回 编号，如果不成功返回 －1*/
int openfile(char * dir)
{
	int fd = 0;
	if((fd =  open(dir , O_RDWR|O_APPEND)) == -1)
	{
		my_err("open", _LINE_);
		return -1;
	}
	else
	{
		printf("open file success\n");
		return fd;
	}
}
/**/
int createfile(char *buff)
{
	int fd;
	if((fd = creat("test.c",S_IREAD)) == -1)
	{
			my_err("open", _LINE_);
			return -1;
	}
	else
	{
			printf("create file success\n");

			if(close(fd) == 0 )
					printf("close success\n");
				else

					printf("close bad \n");

			return fd;
	}

}

/*将缓冲buff 中的内容写进fd 文件中*/
int writetofile(int fd, char *buff)
{
	if (( lseek(fd, 0, SEEK_END)) == -1)
		{
			my_err("lseek", _LINE_);
		}
	if(write(fd, buff, strlen(buff)) != strlen(buff))
	{
		my_err("write", _LINE_);
		return -1;
	}
	else
	{
		printf("write success \n");
		return 1;
	}
}

int my_read(int fd , char *read_buff)
{
	int len;
	int ret;
	if (lseek(fd, 0, SEEK_END) == -1)
	{
		my_err("lseek", _LINE_);
	}
	if ((len =lseek(fd, 0, SEEK_CUR)) == -1)
	{
		my_err("lseek", _LINE_);
	}
	if (( lseek(fd, 0, SEEK_SET)) == -1)
	{
		my_err("lseek", _LINE_);
	}

	//printf("len:%d\n",len);
	if((ret = read(fd, read_buff, len))<0)
	{
		my_err("read",_LINE_);
	}
	//printf("\n");
	return ret;
}

void my_err(const char * err_string, int line)
{
	fprintf(stderr, "line:%d ",line);
	perror(err_string);
	exit(1);
}

